<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="拼团名称" prop="collageName">
              <el-input v-model="queryParams.collageName" placeholder="请输入拼团名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="拼团编码" prop="collageCode">
              <el-input v-model="queryParams.collageCode" placeholder="请输入拼团编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="玩法" prop="playWay">
              <el-select v-model="queryParams.playWay" placeholder="请选择玩法" clearable @keyup.enter="handleQuery">
                <el-option v-for="dict in collage_play_way" :key="dict.value" :value="dict.value" :label="dict.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="collageStatus">
              <el-select v-model="queryParams.collageStatus" placeholder="请选择状态" clearable @keyup.enter="handleQuery">
                <el-option v-for="dict in collage_status" :key="dict.value" :value="dict.value" :label="dict.label" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择开始时间" />
            </el-form-item> -->
            <!-- <el-form-item label="店铺id" prop="shopId">
              <el-input v-model="queryParams.shopId" placeholder="请输入店铺id" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增拼团</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Plus" @click="handleAddBox">新增福盒</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:cardCollage:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Position" :disabled="multiple" @click="handleBatchApproval()">批量提审</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['shop:all:position']" type="success" plain icon="HomeFilled" @click="allListRecommend">全部列表位置推荐</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <div style="margin-top: -15px;">
        <el-tabs v-model="queryParams.collageModule" type="card" @tab-change="handleQuery">
          <el-tab-pane label="全部" name=''></el-tab-pane>
          <el-tab-pane v-for="(dict, index) in collage_module" :key="index" :label="dict.label"
                       :name="dict.value"></el-tab-pane>
        </el-tabs>
      </div>
      <el-table v-loading="loading" :data="cardCollageList" @selection-change="handleSelectionChange" border>
         <el-table-column type="selection" width="55" align="center"  :selectable="selectable"  />
        <!-- <el-table-column label="主键" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="拼团封面" align="center" width="150">
          <template #default="scope">
            <image-preview :src="scope.row.imagePath" width="100px" height="80px"></image-preview>
          </template>
        </el-table-column>
        <el-table-column label="拼团名称" align="center" prop="collageName" width="180"/>
        <el-table-column label="拼团编码" align="center" prop="collageCode" width="180"/>
        <el-table-column label="组队方式" align="center" prop="playWay" width="100" >
          <template #default="scope">
            <dict-tag v-if="scope.row.collageModule != '3'" :options="collage_play_way" :value="scope.row.playWay" />
            <el-tag v-else type="warning">福盒</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="拼团进度" align="center" prop="collageProgress" width="95">
          <template #default="scope">
            <div style="display: flex;align-items: center;justify-content: space-around;">
              <div>{{ scope.row.surplusLot !== undefined && scope.row.surplusLot !== null ? Number(scope.row.lotCount) -
                Number(scope.row.surplusLot) : 0 }}/{{
                  scope.row.lotCount }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
          </template>
        </el-table-column>
        <<el-table-column label="拼团状态" align="center" prop="collageStatus" width="95">
          <template #default="scope">
            <div>
              <dict-tag :options="collage_status" :value="scope.row.collageStatus" />
            </div>
            <div style="margin-top: 10px;" v-if="scope.row.collageStatus == '5' ">
              <el-link type="primary" :underline="true" @click="handleCause(scope.row)">查看原因</el-link>
            </div>
          </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="unitPrice" />
          <el-table-column label="实售金额" align="center" prop="saleTotalPrice" />
          <el-table-column label="优惠金额" align="center" prop="discountTotalAmount" />
          <el-table-column label="商品总价" align="center" prop="totalPrice" />
          <el-table-column  label="操作" align="center" class-name="small-padding" fixed="right" width="130">
            <template v-slot="scope">
              <div >
                <el-button type="text" icon="Position" @click="approvalCollageState(scope.row)"
                  v-if="scope.row.collageStatus == '1' || scope.row.collageStatus == '5'"
                  style="color: #26bf11">提交审核</el-button>
              </div>
              <div>
                <el-button type="text" icon="Top" @click="handleShelf(scope.row)"
                  v-if="scope.row.collageStatus == '3'" style="color: #26bf11"
                  >上架</el-button>
              </div>
              <div >
                <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
                  v-if="scope.row.collageStatus == '1' || scope.row.collageStatus == '5' || scope.row.collageStatus == '3'"
                  >修改</el-button>
              </div>
              <div >
                <el-button type="text" icon="Delete"
                  v-if="scope.row.collageStatus == '1' || scope.row.collageStatus == '3' || scope.row.collageStatus == '5'" @click="handleDelete(scope.row)"
                  >删除</el-button>
              </div>
              <div >
                <el-button type="text" @click="handleView(scope.row)" icon="View"
                  >查看</el-button>
              </div>
              <div >
                <el-button type="text" icon="TurnOff" @click="openGroup(scope.row)"  v-if="scope.row.isOpenRandom == '0' && scope.row.collageStatus == '4'  && scope.row.collageModule != '3' && scope.row.playWay == '4' "
                  >开启剩余</el-button>
              </div>
              <div >
                <el-button type="text" icon="Open" v-if="scope.row.isOpenRandom == '1' && scope.row.collageModule != '3' && scope.row.playWay == '4' " :disabled = "true"
                  >剩余开启</el-button>
              </div>
              <div>
                <el-button type="text" icon="Lock" @click="handleLockUser(scope.row)"
                  v-if="scope.row.collageStatus == '4'">锁单限制</el-button>
              </div>
              <div >
                <el-button type="text" icon="View" @click="handleViewOrder(scope.row)"
                  v-if="scope.row.collageStatus == '4' || scope.row.collageStatus == '7' || scope.row.collageStatus == '9' || scope.row.collageStatus == '6'">查看订单</el-button>
              </div>
              <div >
                <el-button type="text" icon="Histogram" @click="openUserPayStatistics(scope.row)"
                  v-if="scope.row.collageStatus == '4' || scope.row.collageStatus == '6'"
                  >消费统计</el-button>
              </div>
              <div >
                <el-button type="text" icon="Notebook" @click="openUserCarmiStatistics(scope.row)" v-hasPermi="['shop:user:carmi']"
                  v-if="scope.row.collageStatus == '4' || scope.row.collageStatus == '6'"
                  >查看卡密</el-button>
              </div>
              <div v-if="scope.row.collageStatus=='4'">
                <div v-if="scope.row.collageModule=='3'" v-hasPermi="['shop:box:position']">
                  <el-button type="text" icon="Guide" v-if="scope.row.positionStatus=='1'" style="color: #ea0619"
                             @click="recommendPosition(scope.row)">推荐位置-开启</el-button>
                  <el-button type="text" icon="Guide" v-else
                             @click="recommendPosition(scope.row)">推荐位置-关闭</el-button>
                </div>
                <div v-else v-hasPermi="['shop:collage:position']">
                  <el-button type="text" icon="Guide" v-if="scope.row.positionStatus=='1'" style="color: #ea0619"
                             @click="recommendPosition(scope.row)">推荐位置-开启</el-button>
                  <el-button type="text" icon="Guide" v-else
                             @click="recommendPosition(scope.row)">推荐位置-关闭</el-button>
                </div>
              </div>
              <div >
                <el-button type="text" icon="CopyDocument"
                  v-if="scope.row.collageStatus == '1' || scope.row.collageStatus == '3' || scope.row.collageStatus == '5'
                    || scope.row.collageStatus == '6' || scope.row.collageStatus == '7' || scope.row.collageStatus == '8'"
                  @click="handleCopyColloge(scope.row)">复制{{ scope.row.collageModule==3?'福盒':'拼团' }}</el-button>
              </div>
              <div >
                <el-button type="text" icon="CopyDocument"
                  v-if="scope.row.collageStatus == '1' || scope.row.collageStatus == '3' || scope.row.collageStatus == '5'
                    || scope.row.collageStatus == '6' || scope.row.collageStatus == '7' || scope.row.collageStatus == '8'"
                  @click="handleBatchCopyColloge(scope.row)">批量复制{{ scope.row.collageModule==3?'福盒':'拼团' }}</el-button>
              </div>
              <div
                v-if="scope.row.isCollageRanking == '1' && (scope.row.collageStatus == '4' || scope.row.collageStatus == '7' || scope.row.collageStatus == '9' || scope.row.collageStatus == '6')">
                <el-button :loading="buttonLoading" type="text" icon="Trophy" @click="viewCharts(scope.row)">查看拼团榜单</el-button>
              </div>
            </template>
          </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改拼团管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1600px" append-to-body top="3vh" :destroy-on-close="true">
      <cardCollageForm v-if="dialog.visible" :collageId="collageId" :collageModule="collageModule" @submit="submitForm" :isView="isView"
        ref="cardCollageRef1" @cancle="cancel" @submitAgain="submitFormAgain" />
    </el-dialog>
<!--     添加或修改福盒管理对话框 -->
    <el-dialog title="添加福盒管理" v-model="boxDialog.visible" width="1600px" append-to-body top="3vh" destroy-on-close>
      <cardCollageBoxForm v-if="boxDialog.visible" :isView="isView" :collageId="collageId" :collageModule="collageModule" @submit="boxSubmitForm"
        ref="cardCollageRefBox" @cancle="boxCancel"  @submitAgain="submitFormAgain" />
    </el-dialog>

    <el-dialog title="用户锁单限制" v-model="nonPaymentDia.visible" append-to-body width="60%" :destroy-on-close="true">
      <nonPayment :collageId="collageId" />
    </el-dialog>

    <!--消费统计-->
    <el-dialog title="用户消费统计" v-model="userPayFlag.visible" append-to-body width="60%" :destroy-on-close="true" center>
      <userPayStatistics :collageId="collageId" />
    </el-dialog>

    <!--查看卡密-->
    <el-dialog title="查看卡密报告" v-model="userCarmiFlag.visible" append-to-body width="80%" :destroy-on-close="true" center>
      <userCarmiInfo :collageId="collageId" :collageCode="collageCode" :collageName="collageName" :playWay="playWay" />
    </el-dialog>

    <el-dialog title="查看榜单" top="3vh" v-model="openChartsDia.visible" @close="openChartsDia.visible= false" append-to-body width="60%" center
               :destroy-on-close="true">
      <div>
        <el-table v-loading="loading" :data="collageRankingPrizes" border>
          <el-table-column
            label="排名"
            align="center"
            prop="sortNumber"
            width="100px"
          >
            <template #default="scope">
              {{ `第 ${Number(scope.$index) + 1} 名` }}
            </template>
          </el-table-column>
          <el-table-column label="用户信息" align="center" prop="prize" width="300px">
            <template v-slot ="scope">
              <div class="common-flex-image">
                <image-preview
                  style="width: 80px; height: 80px"
                  :src="scope.row.headPortrait">
                </image-preview>
                <div style="width: 180px; margin-left: 20px;text-align: left;font-size: 12px;">
                  <div style="margin-top: 5px;text-align: left;">昵称：{{scope.row.nickName}}</div>
                  <div style="margin-top: 5px;text-align: left;">玩家号：{{scope.row.userInviteCode}}</div>
                  <div style="margin-top: 5px;text-align: left;">购买数量：{{scope.row.carmiNum}}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="奖品" align="left" prop="prize" />
        </el-table>
      </div>
    </el-dialog>

    <!--查看订单-->
    <el-dialog title="查看订单" v-model="orderDia.visible" append-to-body width="1500" :destroy-on-close="true" center>
      <collageOrder :cardCollageId="collageId" :collageCode="collageCode" :shopName="shopName"/>
    </el-dialog>

    <el-dialog title="全部" v-model="allListDia.visible" append-to-body width="1500" :destroy-on-close="true" center>
      <el-form-item>
        <el-button type="primary" icon="Refresh" @click="getAllList">刷新</el-button>
      </el-form-item>
      <el-table v-loading="allListLoading" :data="allCardCollageList" ref="collageTable" border :highlight-current-row="true"
                tooltip-effect="light" max-height="600px">
        <el-table-column label="拼团封面" align="center">
          <template #default="scope">
            <image-preview :src="scope.row.imagePath" width="100px" height="80px"></image-preview>
          </template>
        </el-table-column>
        <el-table-column label="拼团名称" align="center" prop="collageName" :show-overflow-tooltip="true"/>
        <el-table-column label="编码" align="center" prop="collageCode" :show-overflow-tooltip="true"/>
        <el-table-column label="单价" align="center" prop="unitPrice" :show-overflow-tooltip="true"/>
        <el-table-column label="拼团进度" align="center" prop="collageProgress">
          <template #default="scope">
            <div style="display: flex;align-items: center;justify-content: space-around;">
              <div>{{
                  scope.row.surplusLot !== undefined && scope.row.surplusLot !== null ?
                    Number(scope.row.lotCount) - Number(scope.row.surplusLot) : 0
                }}/{{ scope.row.lotCount }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding" fixed="right">
          <template #default="scope">
            <div>
              <el-button type="text" icon="Guide" v-if="scope.row.allPositionStatus=='1'" style="color: #ea0619"
                         @click="recommendAllPosition(scope.row)">全部推荐位置-开启</el-button>
              <el-button type="text" icon="Guide" v-else
                         @click="recommendAllPosition(scope.row)">全部推荐位置-关闭</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="allListTotal > 0" :total="allListTotal" v-model:page="allListQueryParams.pageNum"
                  v-model:limit="allListQueryParams.pageSize" @pagination="getAllList" />
    </el-dialog>

    <el-dialog title="批量复制" v-model="copyCollageDia.visible" append-to-body width="60%" :destroy-on-close="true">
      <div style="padding-bottom: 10px;">
        <el-button type="primary" size="default" icon="Plus" @click="addCopyBatchCollage">添加拼团</el-button>
      </div>
      <div>
        <el-form label-width="80px" :model="copyForm" :inline="false" ref="copyFormRef">
          <el-table :data="copyForm.collageNameList" border max-height="500px" v-loading = "copyLoading">>
              <el-table-column label="序号" align="center" prop="sortNumber" width="90px">
                <template #default="scope">
                  <span style="opacity: 0;">1</span>
                  {{ `序号${Number(scope.$index) + 1}` }}
                  <!-- <span style="opacity: 0;">{{ scope.row.sortNumber = Number(scope.$index) + 1 }}</span> -->
                </template>
              </el-table-column>
              <el-table-column label="拼团名称" align="center" width="750px">
                <template #default="scope">
                  <!-- :rules="copyRules.collageName" -->
                  <el-form-item :prop="'collageNameList.'+scope.$index + '.collageName'"  label-width="0"  :rules="copyRules.collageName"  class="copyBatchCollageName">
                    <el-input v-model="scope.row.collageName" placeholder="请输入拼团名称" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="110px">
                <template #default="scope">
                  <el-popconfirm title="确定要删除该条记录吗？" icon-color="red"
                                 @confirm="handleCopyCollageDelete(scope.$index)">
                    <template #reference>
                      <el-button type="danger" icon="Delete" circle></el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          <div align="center" style="margin-top: 10px;">
            <el-button type="primary" @click="submitCopyForm">确 定</el-button>
            <el-button @click="cancleCopyForm">取 消</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import {
  listCardCollage,
  getCardCollage,
  delCardCollage,
  addCardCollage,
  updateCardCollage,
  openApprovalCollageState,
  copyCardCollage,
  shelfCollageState,
  againChangeCollageState,
  cardCollageRankingList,
  openGroupRandom,
  removeLockUserCollage,
  isExitCollage,
  openCollagePosition, isAllExitCollage, openAllCollagePosition, batchCopyCardCollage, batchOpenApprovalCollageState
} from '@/api/workflow/cardCollage/index';
import {
   cardCollageCopyVo,
  CardCollageFormVo,
  CardCollageRaikingVo,
  CardCollageVO
} from '@/api/workflow/cardCollage/types';
import cardCollageForm from '@/components/cardCollageForm/index.vue';
import cardCollageBoxForm from '@/components/cardCollageBoxForm/index.vue';
import collageOrder from '@/components/collageCom/collageOrder.vue';
import nonPayment from '@/components/collageCom/nonPayment.vue';
import userPayStatistics from '@/components/collageCom/userPayStatistics.vue';
import { aS } from 'vitest/dist/reporters-LqC_WI4d';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { collage_play_way, collage_status, collage_module,} = toRefs<any>(proxy?.useDict('collage_play_way', 'collage_status','collage_module'));
const cardCollageList = ref<CardCollageVO[]>([]);
const allCardCollageList = ref<CardCollageVO[]>([]);
const collageRankingPrizes = ref<CardCollageRaikingVo[]>([]);
const cardCollageCopyList = ref<cardCollageCopyVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const copyLoading = ref(false);
const allListLoading = ref(true);
const showSearch = ref(true);
const allShowSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const allListTotal = ref(0);
const collageId = ref();
const collageCode = ref();
const collageName = ref();
const playWay = ref();
const shopName = ref();
const collageModule = ref();
const queryFormRef = ref<ElFormInstance>();
const cardCollageRef1 = ref();
const cardCollageRefBox = ref();
const isView = ref(false);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const boxDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const nonPaymentDia = reactive<DialogOption>({
  visible: false,
  title: ''
});

const orderDia = reactive<DialogOption>({
  visible: false,
  title: ''
});

const openChartsDia = reactive<DialogOption>({
  visible: false,
  title: ''
});

const userPayFlag = reactive<DialogOption>({
  visible: false,
  title: ''
});

const userCarmiFlag = reactive<DialogOption>({
  visible: false,
  title: ''
});

const allListDia = reactive<DialogOption>({
  visible: false,
  title: ''
});

const copyCollageDia = reactive<DialogOption>({
  visible: false,
  title: ''
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    collageName: undefined,
    collageCode: undefined,
    collageModule: '',
    playWay: undefined,
    collageStatus: undefined,
  },
  allListQueryParams: {
    pageNum: 1,
    pageSize: 10,
    collageName: undefined,
    collageCode: undefined,
    collageModule: '',
    playWay: undefined,
    collageStatus: undefined,
  },
  copyForm: {
   collageNameList:[],
   collageId:[],
  },
  copyRules:{
    collageName: [
      { required: true, message: '请输入拼团名称', trigger: 'blur' },
    ],
  }
});

const { queryParams, allListQueryParams, copyForm,copyRules } = toRefs(data);
const CopyRow = ref<any>({}); //备份选中的拼团
/** 查询拼团管理列表 */
const getList = async () => {
    loading.value = true;
    const res = await listCardCollage(queryParams.value);
    cardCollageList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;

}

/** 取消按钮 */
const boxCancel = () => {
  reset();
  boxDialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  cardCollageRef1.value = '';
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: CardCollageVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  // reset();
  collageModule.value = '';
  dialog.visible = true;
  dialog.title = "添加拼团管理";
  isView.value = false;
  collageId.value = '';
}

const handleView = async (row: CardCollageVO) => {
  collageId.value = row?.id;
  isView.value = true;
  if(Number(row.collageModule)==3){
    boxDialog.visible = true;
    boxDialog.title = "查看福盒管理";
  }else{
    dialog.visible = true;
    dialog.title = "查看拼团管理";
  }
}

const handleLockUser = async (row: CardCollageVO) => {
  collageId.value = row?.id;
  nonPaymentDia.visible = true;
}

/** 新增福盒按钮操作 */
const handleAddBox = () => {
  collageModule.value = '3';
  boxDialog.visible = true;
  boxDialog.title = "添加福盒管理";
  isView.value = false;
  collageId.value = ''
}

/** 修改按钮操作 */
const handleUpdate = async (row?: CardCollageVO) => {
  // dialog.visible = true;
  // dialog.title = "修改拼团管理";
  collageId.value = row?.id;
  isView.value = false;
  if(Number(row.collageModule)==3){
    boxDialog.visible = true;
    boxDialog.title = "修改福盒管理";
  }else{
    dialog.visible = true;
    dialog.title = "修改拼团管理";
  }
}
/**
 * 查看原因
 */
const handleCause = async (row?: CardCollageVO) => {
  const res = await getCardCollage(row?.id);
  let msg;
  if(res.code == 200) {
    msg = res.data.cardCollageDetailVo.cause;
  } else {
    msg = "请联系客服";
  }
  ElMessageBox.alert(msg, '原因', {
    confirmButtonText: 'OK',
  });
}

/** 提交按钮 */
const submitForm = (data: CardCollageFormVo) => {
  if (data.id) {
    updateCardCollage(data).then((res) => {
      proxy?.$modal.msgSuccess("操作成功");
      reset();
      dialog.visible = false;
      getList()
    });
  } else {
    addCardCollage(data).then((res) => {
      proxy?.$modal.msgSuccess("操作成功");
      reset();
      dialog.visible = false;
      getList()
    });
  }

  // await getList();
}

const viewCharts = async (row?: CardCollageVO) => {
  //查询
  openChartsDia.visible = true
  const res = await cardCollageRankingList(row.id);
  if(res.code==200) {
    collageRankingPrizes.value = res.data.cardCollageRaikingVos;
  }
}

const openGroup = async (row?: CardCollageVO) => {
  await proxy.$modal.confirm('确定开启"' + row.collageCode + '"的剩余随机么？').finally(() => loading.value = false);
  const res = await openGroupRandom(row.id);
  if(res.code == 200) {
    await getList();
    proxy?.$modal.msgSuccess("操作成功");
  }
}

const submitFormAgain = (data: CardCollageFormVo) => {
  againChangeCollageState(data).then((res) => {
    proxy?.$modal.msgSuccess("操作成功");
    reset();
    dialog.visible = false;
    boxDialog.visible = false;
    getList()
  });
}

/** 提交按钮 */
const boxSubmitForm = (data: CardCollageFormVo) => {
  if (data.id) {
      updateCardCollage(data).then((res) => {
      proxy?.$modal.msgSuccess("操作成功");
      reset();
      dialog.visible = false;
      boxDialog.visible = false;
      getList()
    });
  } else {
      addCardCollage(data).then((res) => {
      proxy?.$modal.msgSuccess("操作成功");
      reset();
      dialog.visible = false;
        boxDialog.visible = false;
      getList()
    });
  }
  // await getList();
}

const approvalCollageState = async (row: CardCollageVO) => {
    const _ids = row?.id || ids.value;
    await proxy.$modal.confirm('提交审核"' + row.collageCode + '"的数据项？').finally(() => loading.value = false);
    await openApprovalCollageState(_ids);
    proxy?.$modal.msgSuccess("提审成功");
    await getList();
}

// 禁用删除数据线
const selectable = (row: CardCollageVO) => {
  return row.collageStatus == '1'|| row.collageStatus == '5';
}

/** 删除按钮操作 */
const handleDelete = async (row?: CardCollageVO) => {
  const _ids = row?.id || ids.value;
  let code = "";
  if(Object.prototype.toString.call(_ids) === '[object String]'){
    code = '是否确认删除拼团管理编号为"' + row.collageCode + '"的数据项？';
  }else{
    code = '是否确认删除选中的数据项？';
  }
  await proxy?.$modal.confirm(code).finally(() => loading.value = false);
  await delCardCollage(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 批量审核按钮操作 */
const handleBatchApproval = async (row?: CardCollageVO) => {
  const _ids = row?.id || ids.value;
  let code = "";
  if(Object.prototype.toString.call(_ids) === '[object String]'){
    code = '是否审核拼团管理编号为"' + row.collageCode + '"的数据项？';
  }else{
    code = '是否确认审核选中的数据项？';
  }
  await proxy?.$modal.confirm(code).finally(() => loading.value = false);
  const res = await batchOpenApprovalCollageState(_ids);
  if(res.code == 200) {
    proxy?.$modal.msgSuccess("审核成功");
  } else {
    proxy?.$modal.msgError(res.msg);
  }
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/cardCollage/export', {
    ...queryParams.value
  }, `cardCollage_${new Date().getTime()}.xlsx`)
}

/**
 * 消费统计
 * @param row
 */
const openUserPayStatistics =async (row: CardCollageVO) => {
  collageId.value = row?.id;
  userPayFlag.visible = true
}

/**
 * 查看卡密
 * @param row
 */
const openUserCarmiStatistics =async (row: CardCollageVO) => {
  collageId.value = row?.id;
  collageCode.value = row?.collageCode;
  playWay.value = row?.playWay;
  collageName.value = row?.collageName;
  userCarmiFlag.visible = true
}

/**
 * 推荐位置
 * @param row
 */
const recommendPosition = async (row: CardCollageVO) => {
  let positionStatus = "";
  let str = "";
  if(row.positionStatus == '0') { //关闭=>开启
    positionStatus = '1';
    var res = await isExitCollage(row.collageModule);
    if(res.code == 200) {
      str = "推荐位置开启后，该拼团将出现在首页推荐位置，是否继续开启？";
    } else {
      str = "推荐位置的拼团已存在，操作后将替换推荐位置上的拼团，是否继续？";
    }
  } else if(row.positionStatus == '1') { //开启=>关闭
    positionStatus = '0';
    str = "推荐位置关闭后，该拼团将不再出现在首页推荐位置，是否继续关闭？";
  }
  ElMessageBox.confirm(str, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    openCollagePosition({ collageId: row?.id, positionStatus: positionStatus }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
        getList();
      }
    });
  }).catch(() => {});

}

/**
 * 全部位置
 * @param row
 */
const recommendAllPosition = async (row: CardCollageVO) => {
  let allPositionStatus = "";
  let str = "";
  if(row.allPositionStatus == '0') { //关闭=>开启
    allPositionStatus = '1';
    var res = await isAllExitCollage();
    if(res.code == 200) {
      str = "推荐位置开启后，该拼团将出现在首页推荐位置，是否继续开启？";
    } else {
      str = "推荐位置的拼团已存在，操作后将替换推荐位置上的拼团，是否继续？";
    }
  } else if(row.allPositionStatus == '1') { //开启=>关闭
    allPositionStatus = '0';
    str = "推荐位置关闭后，该拼团将不再出现在首页推荐位置，是否继续关闭？";
  }
  ElMessageBox.confirm(str, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    openAllCollagePosition({ collageId: row?.id, allPositionStatus: allPositionStatus }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
        getAllList();
      }
    });
  }).catch(() => {});

}

const handleBatchCopyColloge = (row:any) => {
  CopyRow.value = row;
  copyForm.value = {
    collageId: row.id,
    collageNameList: [{ collageName: row.collageName}],
  }
   copyCollageDia.visible =  true;
}

const addCopyBatchCollage = () => {
  copyForm.value.collageNameList.push({collageName:CopyRow.value?.collageName});
}

const handleCopyCollageDelete = (index:number)=>{
  copyForm.value.collageNameList.splice(index, 1);
}

const submitCopyForm = async () => {
  proxy.$refs?.copyFormRef?.validate(async (valid: boolean) => {
    if (valid) {
      let formData ={
        collageId: copyForm.value.collageId,
        collageNameList: copyForm.value.collageNameList.map(item => item.collageName)
      }
      try {
        copyLoading.value = true;
        const response = await batchCopyCardCollage(formData);
        if (response.code === 200) {
          proxy?.$modal.msgSuccess("批量复制拼团成功");
          copyLoading.value = false;
          copyCollageDia.visible = false;
          getList();
        } else {
          proxy?.$modal.msgError("批量复制拼团失败");
        }
      } catch (error) {
      } finally {
        copyLoading.value = false;
      }
    }else{
      proxy?.$modal.msgError("请填写完整");
    }
  });
}

const cancleCopyForm = () => {
  copyCollageDia.visible =  false;
  proxy.$refs?.copyFormRef?.resetFields();
}
/**  复制拼团  **/
const handleCopyColloge = async (row: CardCollageVO) => {
  try {
    await proxy?.$modal.confirm(`是否确认复制标题为【${row.collageName}】的拼团吗？`);
    loading.value = true;
    const response = await copyCardCollage(row.id);
    if (response.code === 200) {
      proxy?.$modal.msgSuccess("复制拼团成功");
      getList();
    } else {
      proxy?.$modal.msgError("复制拼团失败");
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

const handleShelf = async (row: CardCollageVO) => {
  const _ids = row?.id
  await proxy.$modal.confirm('是否确认上架编号为"' + row.collageCode + '"的' + (Number(row.collageModule) == 3 ? '福盒' : '拼团')).finally(() => loading.value = false);
  loading.value = true;
  try {
    const response = await shelfCollageState(row.id);
    if (response.code === 200) {
      proxy?.$modal.msgSuccess("上架拼团成功");
    } else {
      proxy?.$modal.msgError("上架拼团失败");
    }
  } catch (e) {
    loading.value = false;
  }
  loading.value = false;
  getList();
}

const handleViewOrder = (row?: CardCollageVO) => {
  collageId.value = row?.id;
  collageCode.value = row?.collageCode;
  shopName.value = row?.shopName;
  orderDia.visible = true
}

const allListRecommend = () => {
  allListDia.visible = true;
  getAllList();
}

const getAllList = async () => {
  allListLoading.value = true;
  allListQueryParams.value.collageStatus = '4';
  const res = await listCardCollage(allListQueryParams.value);
  allCardCollageList.value = res.rows;
  allListTotal.value  = res.total;
  allListLoading.value = false;
}


onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>

::v-deep(.copyBatchCollageName){
  margin-top:20px ;
}
</style>
